package vn.gq.tym.comictemplate;

import java.util.ArrayList;

import org.json.JSONObject;

import vn.gq.tym.model.item.AdmobItem;
import vn.gq.tym.scr.ImageViewScr;
import vn.gq.tym.utils.AdmobAdsHandler;
import vn.gq.tym.utils.Client;
import vn.gq.tym.utils.DataType;
import vn.gq.tym.utils.IClientListener;
import vn.gq.tym.utils.NetworkOption;
import vn.gq.tym.widget.OnViewPagerDisablePagingListener;
import vn.gq.tym.widget.PopupWindow;
import vn.gq.tym.widget.SwipeyTabs;
import vn.gq.tym.widget.SwipeyTabsAdapter;
import vn.gq.tym.widget.ViewPager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.ironsource.mobilcore.CallbackResponse;
import com.ironsource.mobilcore.MobileCore;
import com.nostra13.universalimageloader.core.ImageLoader;


public class ReaderActivity extends FragmentActivity implements OnViewPagerDisablePagingListener, OnDoubleTapListener, OnClickListener {

	public static final String EXTRA_IMAGES_LIST = "EXTRA_IMAGES_LIST";
	public static final String EXTRA_POSITION = "EXTRA_POSITION";
	private static final String STATE_POSITION = "STATE_POSITION";
	
	private ArrayList<String> mImageList;
	private int mCurrentPos = 0;
	private SwipeyTabs mTabs;
	private ViewPager mViewPager;
	private ImageLoader imagerLoader = ImageLoader.getInstance();
	private PopupWindow mPopupWindow;
	private LinearLayout mLayoutContainer;
	private AdmobAdsHandler mAdsHandler;
	private Handler mHandler = new Handler();
	private Button btnOk, btnFirst, btnLast;
	private EditText editText;
	
	public void setLastTimeShowedMCAds(long time) {
		SharedPreferences pref = getSharedPreferences(getClass().getSimpleName(), MODE_PRIVATE);
		Editor ed = pref.edit();
		ed.putLong("cfg_show_ad_time", time);
		ed.commit();
	}
	
	public long getLastTimeShowedMCAds() {
		SharedPreferences pref = getSharedPreferences(getClass().getSimpleName(), MODE_PRIVATE);
		long val = pref.getLong("cfg_show_ad_time", 0);
		return val;
	}
	
	private Runnable mcAdRun = new Runnable() {
		
		@Override
		public void run() {
			final long currentTime = System.currentTimeMillis();
			if (currentTime - getLastTimeShowedMCAds() >= 30000) {
				MobileCore.showOfferWall(ReaderActivity.this, new CallbackResponse() {
	
					@Override
					public void onConfirmation(TYPE ad) {
						setLastTimeShowedMCAds(currentTime);
					}
					
				});
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_reader);
		MobileCoreHelper.init(this);
		mLayoutContainer = (LinearLayout) findViewById(R.id.reader_container);
		mImageList = getIntent().getExtras().getStringArrayList(EXTRA_IMAGES_LIST);
		mCurrentPos = getIntent().getExtras().getInt(EXTRA_POSITION);
		
		// Setup Admob Ads
		LinearLayout adLayout = (LinearLayout) findViewById(R.id.adLayout);
		AdmobItem aUnitId = AdmobItem.load(getApplicationContext());
		if (BuildConfig.DEBUG) {
			Log.e("longhoanggiang", "ad = "+aUnitId.getAdsTypeBanner());
		}
		AdView adView = new AdView(this, AdSize.SMART_BANNER, aUnitId.getAdsTypeBanner());
		adLayout.addView(adView);
		mAdsHandler = new AdmobAdsHandler(this, adView);
		
		if (savedInstanceState != null) {
			mCurrentPos = savedInstanceState.getInt(STATE_POSITION);
		}
		ImagePagerAdapter adapter = new ImagePagerAdapter(getSupportFragmentManager(), mImageList);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		mTabs.setAdmobAdsHandler(mAdsHandler);
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setCurrentItem(mCurrentPos);
		initializePopupWindow();
		Toast.makeText(this, getString(R.string.have_a_nice), Toast.LENGTH_SHORT).show();
		if (!aUnitId.isLoaded()) {
			loadAdmId();
		}
		mHandler.postDelayed(mcAdRun, 500);
	}
	
	public void initializePopupWindow() {
		mPopupWindow = new PopupWindow(this);
		ViewGroup popupView = (ViewGroup) getLayoutInflater().inflate(R.layout.popup, null, false);
		mPopupWindow.setContentView(popupView);
		btnFirst = (Button) popupView.findViewById(R.id.first);
		btnFirst.setOnClickListener(this);
		btnLast = (Button) popupView.findViewById(R.id.last);
		btnLast.setOnClickListener(this);
		btnOk = (Button) popupView.findViewById(R.id.enter);
		btnOk.setOnClickListener(this);
		editText = (EditText) popupView.findViewById(R.id.page_num);
	}
	
	public void loadAdmId() {
		Client client = new Client(getApplicationContext());
		client.setCacheTime(3600000); // cache in 1 hour
		client.setNetworkOption(NetworkOption.OPTION_USE_CACHE);
		client.setOutputDataType(DataType.JSON);
		client.executeAndListener(String.format("http://apps.cucdinh.vn/ads/admob?id=%s&t=text", getPackageName()), new IClientListener() {
			
			@Override
			public void onDone(int code, Object result) {
				if (BuildConfig.DEBUG) {
					Log.e("longhoanggiang", String.valueOf(result));
				}
				AdmobItem admobItem = null;
				if (code < 1 && (result != null)) {
					
					admobItem = new AdmobItem((JSONObject) result);
					admobItem.setLoaded(true);
					admobItem.setPreference(getApplicationContext());
					if (BuildConfig.DEBUG) {
						Log.e("longhoanggiang", "banner = "+admobItem.getAdsTypeBanner());
						Log.e("longhoanggiang", "fullscreen = "+admobItem.getAdsTypeFullScreen());
					}
				}
			}
		});
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, mCurrentPos);
		super.onSaveInstanceState(outState);
	}

	public static void startActivity(Context context, ArrayList<String> imageList, int position) {
		Intent intent = new Intent(context, ReaderActivity.class);
		intent.putExtra(EXTRA_IMAGES_LIST, imageList);
		intent.putExtra(EXTRA_POSITION, position);
		context.startActivity(intent);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mAdsHandler.loadAds();
	}

	private class ImagePagerAdapter extends FragmentStatePagerAdapter implements SwipeyTabsAdapter {
		
		
		private ArrayList<String> images;
		private LayoutInflater mInflater;
		
		public ImagePagerAdapter(FragmentManager fm, ArrayList<String> images) {
			super(fm);
			this.images = images;
			mInflater = getLayoutInflater();
		}

		@Override
		public Fragment getItem(int position) {
			return ImageViewScr.newInstance(images.get(position));
		}

		@Override
		public int getCount() {
			return images.size();
		}

		@Override
		public TextView getTab(final int position, SwipeyTabs root) {
			TextView view = (TextView) mInflater.inflate(
					R.layout.swipey_tab_indicator, root, false);
			view.setText(String.format("%d/%d", position + 1, getCount()));
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			
			return view;
		}
	}

	@Override
	public void onDisable(boolean val) {
		if (val) {
			mViewPager.setPagingEnable(false);
		} else {
			mViewPager.setPagingEnable(true);
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		imagerLoader.stop();
		mAdsHandler.onStop();
	}

	@Override
	public void onBackPressed() {
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
		Bookmark.savePosition(this, mViewPager.getCurrentItem());
		super.onBackPressed();
	}

	@Override
	public boolean onSingleTapConfirmed(MotionEvent e) {
		
		if (!mPopupWindow.isShowing()) {
			mPopupWindow.showAtLocation(mLayoutContainer, Gravity.CENTER, 0, 0);
		} else {
			mPopupWindow.dismiss();
		}
		
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mAdsHandler.onDestroy();
	}

	@Override
	public boolean onDoubleTap(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onDoubleTapEvent(MotionEvent e) {
		return false;
	}

	@Override
	public void onClick(View v) {
		if (v.equals(btnFirst)) {
			if (mViewPager.getCurrentItem() > 0) mViewPager.setCurrentItem(0);
		} else if (v.equals(btnLast)) {
			if (mViewPager.getCurrentItem() < mImageList.size() - 1) mViewPager.setCurrentItem(mImageList.size() - 1);
		} else if (v.equals(btnOk)) {
			try {
				Integer page = Integer.parseInt(editText.getText().toString());
				page--;
				if (page >=0 && (page <=mImageList.size()-1)) {
					if (page != mViewPager.getCurrentItem()) {
						mViewPager.setCurrentItem(page);
					}
				}
			} catch(Exception e) {
			}
		}
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
	}
}
